﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KJSyncXP.Extensions
{
    public static class HexConverter
    {
        public static byte[] FromHexString(string hexString)
        {
            if (hexString == null)
                throw new ArgumentNullException(nameof(hexString));

            // 处理可能的前缀（如 "0x"）
            if (hexString.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                hexString = hexString.Substring(2);
            }

            // 检查长度是否为偶数 
            if (hexString.Length % 2 != 0)
            {
                throw new ArgumentException("Hex string must have an even number of characters.", nameof(hexString));
            }

            // 移除所有空白字符
            hexString = new string(hexString.Where(c => !char.IsWhiteSpace(c)).ToArray());

            byte[] result = new byte[hexString.Length / 2];

            for (int i = 0; i < result.Length; i++)
            {
                string hexByte = hexString.Substring(i * 2, 2);
                result[i] = HexByteToByte(hexByte);
            }

            return result;
        }

        private static byte HexByteToByte(string hexByte)
        {
            if (hexByte.Length != 2)
                throw new ArgumentException("Hex byte must be exactly 2 characters long.", nameof(hexByte));

            byte highNibble = HexCharToByte(hexByte[0]);
            byte lowNibble = HexCharToByte(hexByte[1]);

            return (byte)((highNibble << 4) | lowNibble);
        }

        private static byte HexCharToByte(char c)
        {
            if (c >= '0' && c <= '9')
            {
                return (byte)(c - '0');
            }
            else if (c >= 'A' && c <= 'F')
            {
                return (byte)(10 + (c - 'A'));
            }
            else if (c >= 'a' && c <= 'f')
            {
                return (byte)(10 + (c - 'a'));
            }
            else
            {
                throw new ArgumentException($"Invalid hex character: {c}");
            }
        }
    }
}
